---------------------------------------------------
---------------------------------------------------
---------------------------------------------------
For the Main Activity:
import android.view.View;
public void onClick(View v) {
View vButton = findViewById(R.id.mybutton);
View vText = findViewById(R.id.myText);
if (counter == 0) {
vText.setVisibility(View.VISIBLE);
vButton.setVisibility(View.GONE);
counter++;
} else {
vText.setVisibility(View.GONE);
vButton.setVisibility(View.VISIBLE);
counter=0; }
}
---------------------------------------------------
Miscellaneous Notes on button clicks:
---------------------------------------------------
Using Variables:
CheckBox chkbx1 = (CheckBox) findViewById(R.id.***);
Button button1 = (Button) findViewById(R.id.button1);
TextView topLeft = (TextView) findViewById(R.id.textView2);
To put a listener on a button do this:
button1.setOnClickListener( this );
public void onClick(View v) {
}
}
2 ways to handle the click event in button
Onclick in xml layout
Using an OnClickListener
In the interface XML layout file
In MainActivity.java
/** Called when the user touches the button */
public void sendMessage(View view)
{
// Do something in response to button click
}
Make sure your sendMessage method has the following:
Set of public
Return void
Define a View as its only parameter (this will be the View that was clicked)
How to use a listener:
In the Layout file use:
In the MainActivity Code use:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button mButton;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mButton = findViewById(R.id.button_send);
mButton.setOnClickListener(this);
}
@Override
public void onClick(View view)
{
switch (view.getId()) {
case R.id.button_send:
// Do something
}
}
}
Or, use an anonymous listener:
public class MainActivity extends AppCompatActivity {
private Button mButton;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mButton = findViewById(R.id.button_send);
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view)
{
// Do something
}
});
}
}